/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.service.impl;

import com.huawei.housekeeper.entity.MessageServiceEntity;
import com.huawei.housekeeper.utils.JsonUtil;
import com.huawei.housekeeper.dao.entity.Message;
import com.huawei.housekeeper.dao.mapper.MessageMapper;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 接收消息，存入数据库
 *
 * @since 2022-02-15
 */
@Service
public class RabbitmqServiceImpl {

    @Autowired
    private MessageMapper messageMapper;

    /**
     * 从消息队列获取消息
     *
     * @param body json
     * @param headers 请求头
     * @throws JsonProcessingException json转换异常
     */
    @RabbitListener(queues = "message.queue")
    public void receiveMessageFromUserInfo(@Headers Map<String, Object> headers, @Payload String body)
        throws JsonProcessingException {
        String infoFrom = (String) headers.get("amqp_receivedRoutingKey");
        String[] split = infoFrom.split("\\.");
        insertMessage(split[1], body);
    }

    /**
     * 将消息加入数据库
     *
     * @param from 消息来源
     * @param message 消息
     * @throws JsonProcessingException json异常
     */
    private void insertMessage(String from, String message) throws JsonProcessingException {
        MessageServiceEntity messageServiceEntity = JsonUtil.jsonToPojo(message, MessageServiceEntity.class);
        Message newMessage = new Message();
        newMessage.setUserId(messageServiceEntity.getUserId());
        newMessage.setTitle(messageServiceEntity.getTitle());
        newMessage.setContent(messageServiceEntity.getMsg());
        newMessage.setLink(messageServiceEntity.getLink());
        newMessage.setInfoFrom(from);
        newMessage.setCreatedTime(messageServiceEntity.getTime());
        messageMapper.insert(newMessage);
    }

}
